<?php

namespace addons\xpframework\library\xcore\xcore\utils;

use think\Request;

/**
 * Http 请求的工具封装类
 */
class XcRequestUtils
{
    private static $cache_request_value = [
        "get" => [],
        "post" => [],
        "param" => [],
        "header" => [],
    ];
 

    public static function action()
    {
        $request = Request::instance();
        return $request->action();
    }


    /**
     * 在request的基础上增加了是否必填和默认值
     *
     * 示例:XcRequestUtils::header("username", false, "csm");
     * @return string
     */
    public static function header($paramname, $isRequired = false, $defaultValue = null, $requiredErrmsg = null)
    {
        $paramvalue = static::_getValueFromCacherequest("header", $paramname);
        return static::_processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg);
    }

    /**
     * setGet("id", 100)
     * @return void
     */
    public static function setGet($paramname, $paramvalue)
    {
        static::_setValueToCacherequestt("get", $paramname, $paramvalue);
    }
    /**
     * XcRequestUtils::get("id",false,"1");
     * XcRequestUtils::get(["id","ids"],false,"1");
     * @return string
     */
    public static function get($paramname, $isRequired = false, $defaultValue = null, $requiredErrmsg = null)
    {
        $paramvalue = static::_getValueFromCacherequest("get", $paramname);
        return static::_processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg);
    }



    public static function token()
    {
        $request = Request::instance();
        return $request->token();
    }

    public static function setParam($paramname, $paramvalue)
    {
        static::_setValueToCacherequestt("param", $paramname, $paramvalue);
    }
    /**
     * 在request的基础上增加了是否必填和默认值
     *
     * 示例:XcRequestUtils::param("username",false,"csm");
     * @return string
     */
    public static function param($paramname, $isRequired = false, $defaultValue = null, $requiredErrmsg = null)
    {
        $paramvalue = static::_getValueFromCacherequest("param", $paramname);
        return static::_processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg);
    }

    public static function setPost($paramname, $paramvalue)
    {
        static::_setValueToCacherequestt("post", $paramname, $paramvalue);
        // static::$cache_post[$paramname] = $paramvalue;
    }

    /**
     * 在post的基础上增加了是否必填和默认值
     *
     * 示例:XcRequestUtils::post("username",false,"csm");
     * @return string|array
     */
    public static function post($paramname, $isRequired = false, $defaultValue = null, $requiredErrmsg = null)
    {
        $paramvalue = static::_getValueFromCacherequest("post", $paramname);
        return static::_processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg);
    }

    /**
     * 在post body的基础上增加了是否必填和默认值
     *
     * @param string $paramname
     * @param boolean $isRequired
     * @param string $defaultValue
     * @return mixed
     */
    public static function requestJsonBody($paramname, $isRequired = false, $defaultValue = null, $requiredErrmsg = null)
    {
        $body = static::requestBodyJson();
        $paramvalue = isset($body[$paramname]) ? $body[$paramname] : null;
        return static::_processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg);
    }

    public static function requestBodyJson()
    {
        $request = Request::instance();
        $body = json_decode($request->getInput(), true);
        return $body ? $body : [];
    }

    public static function getHttpRefer()
    {
        if (isset($_SERVER['HTTP_REFERER'])) {
            $tt = $_SERVER['HTTP_REFERER'];
            if (str_ends_with($tt, "/")) {
                $tt = substr($tt, 0, strlen($tt) - 1);
            }
            return $tt;
        } else {
            return "";
        }
    }

  

    // // 相比较cdnurl差别是返回全路径
    // public static function cdnurl($url, $domain = true)
    // {
    //     if (empty($url)) {
    //         return '';
    //     }
    //     if (strpos(strtolower($url), "http://") === false && strpos(strtolower($url), "https://") === false) {
    //         $url = cdnurl($url, true);
    //     }
    //     if (strpos(strtolower($url), "http://") === false && strpos(strtolower($url), "https://") === false) {
    //         $url = $_SERVER["REQUEST_SCHEME"] . "://" . $_SERVER["SERVER_NAME"] . $url;
    //     }
    //     return $url;
    // }

    // public static function cdnurls($urls)
    // {
    //     $sr = [];
    //     $urlarray = explode(",", $urls);
    //     foreach ($urlarray as $url) {
    //         $sr[] = static::cdnurl($url, true);
    //     }
    //     return implode(",", $sr);
    // }


    public static function isAjax()
    {
        return  Request::instance()->isAjax();
    }

    public static function getReqest()
    {
        return Request::instance();
    }

    /**
     * URL增加 Get 参数
     *
     * @param string $url, 比如 http://www.example.com
     * @param array $params, 比如 ["id"=>"1", "name"=>"A01"]
     * @return string 比如 http://www.example.com?id=1&name=A01
     */
    public static function appendUrlParams($url, $params)
    {
        $sep = "&";
        if (strpos($url, "?") == false) {
            $sep = "?";
        }
        foreach ($params as $key => $value) {
            $url .= $sep . $key . "=" . urlencode($value);
            $sep = "&";
        }
        return $url;
    }

    public static function getBuildCustomParams($key)
    {
        $custom = (array)XcRequestUtils::get("custom/a");
        if ($custom && is_array($custom)) {
            foreach ($custom as $k => $v) {
                $sr = null;
                if (is_array($v) && 2 == count($v)) {
                    $sr = [$k, trim($v[0]), $v[1]];
                } else {
                    $sr = [$k, '=', $v];
                }
                if ($key == $k) {

                    return $sr;
                }
            }
        }
        return ['', '', ''];
    }

    private static function _setValueToCacherequestt($requestType, $paramname, $paramvalue)
    {
        static::$cache_request_value[$requestType][$paramname] = $paramvalue;
    }
    /**
     * _getValueFromCacherequest("get", "id");
     * _getValueFromCacherequest("get", ["ids", "id"]);
     * @return string
     */
    private static function _getValueFromCacherequest($requestType, $paramname)
    {
        $paramvalue = null;
        if (is_array($paramname)) {
            foreach ($paramname as $item) {
                if (isset(static::$cache_request_value[$requestType][$item])) {
                    $paramvalue = static::$cache_request_value[$requestType][$item];
                } else {
                    $paramvalue = static::_getValueFromRealrequest($requestType, $item);
                }
                if (!empty($paramvalue)) {
                    break;
                }
            }
        } else {
            if (isset(static::$cache_get[$paramname])) {
                $paramvalue = static::$cache_request_value[$requestType][$paramname];
            } else {
                $paramvalue = static::_getValueFromRealrequest($requestType, $paramname);
            }
        }
        return $paramvalue;
    }
    private static function _getValueFromRealrequest($requestType, $paramname)
    {
        $request = Request::instance();
        $request->filter(['strip_tags', 'trim']);

        $paramvalue = null;
        switch ($requestType) {
            case "get":
                $paramvalue = $request->request($paramname);
                break;
            case "post":
                $paramvalue = $request->post($paramname);
                break;
            case "param":
                $paramvalue = $request->param($paramname);
                break;
            case "header":
                $paramvalue = $request->header($paramname);
                break;
            default:
                $paramvalue = $request->request($paramname);
                break;
        }
        return $paramvalue;
    }

    private static function _processRequiredAndDefaultvalue($paramname, $paramvalue, $isRequired, $defaultValue, $requiredErrmsg)
    {
        if (is_string($paramvalue)) {
            $tt = trim(strtolower($paramvalue));
            if ($tt == 'null' || $tt == 'undefined') {
                $paramvalue = null;
            }
            $paramvalue = (empty($paramvalue)) ? null : trim($paramvalue);

            // if ($isRequired == true && ($paramvalue == "" || trim($paramvalue) == "")) {
            //     $msg = "info." . $paramname . "_required";
            //     XcResponseUtils::error($msg);
            // }
        }
        
        if ($isRequired == true && empty($paramvalue)) {
            $msg = ($requiredErrmsg) ? $requiredErrmsg : "info." . $paramname . "_required";
            XcResponseUtils::error($msg);
        }
        if (empty($paramvalue)) {
            $paramvalue = $defaultValue;
        }
        return $paramvalue;
    }
    
}
